package com.pateo.bjev.bjevvehicle;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;

import com.pateo.bjev.bjevvehicle.ui.fragment.PowerSaverFragment;
import com.pateo.bjev.bjevvehicle.ui.fragment.PowerSummaryFragment;
import com.pateo.bjev.bjevvehicle.ui.fragment.VehicleInfoFragment;
import com.pateo.bjev.bjevvehicle.ui.widget.TabLayout;

import java.util.ArrayList;
import java.util.List;

public class HomeActivity extends FragmentActivity {
    TabLayout titleTab;
    ViewPager mPager;
    private VehiclePagerAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        titleTab = (TabLayout) findViewById(R.id.tab_title);
        mPager = (ViewPager) findViewById(R.id.pager);
        bindTabView();
        bindPagerView();
    }

    private void bindPagerView() {

        mAdapter = new VehiclePagerAdapter(getSupportFragmentManager());
        mPager.setAdapter(mAdapter);
        mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                titleTab.selectPosition(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void bindTabView() {

        titleTab.addTab(titleTab.newTab().setText(R.string.title_vehicle_info));
        titleTab.addTab(titleTab.newTab().setText(R.string.title_power_summary));
        titleTab.addTab(titleTab.newTab().setText(R.string.title_power_save));
        titleTab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(int position) {
                mPager.setCurrentItem(position);
            }
        });
    }

    public class VehiclePagerAdapter extends FragmentStatePagerAdapter {
        List<Fragment> mFragments = new ArrayList<>();

        public VehiclePagerAdapter(FragmentManager fm) {
            super(fm);
            mFragments.add(VehicleInfoFragment.newInstance());
            mFragments.add(PowerSummaryFragment.newInstance());
            mFragments.add(PowerSaverFragment.newInstance());
        }

        @Override
        public int getCount() {
            return mFragments.size();
        }

        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }
    }
}
